package com.dimao.certificate_build_service.http.kotiln

import com.dimao.certificate_build_service.http.Api
import com.dimao.certificate_build_service.http.FailedReply
import com.dimao.certificate_build_service.http.SucceededReply
import com.dimao.certificate_build_service.pdf.kotiln.PDFBuilder
import io.vertx.core.buffer.Buffer
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.coroutines.awaitResult
import io.vertx.kotlin.coroutines.dispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import java.util.*

class ShowSinglePDFApi : Api, AsyncApi<String> {
    @ExperimentalCoroutinesApi
    override fun run(context: RoutingContext?) {
        val future = GlobalScope.async (context!!.vertx().dispatcher()) { asyncRun(context) }
        future.invokeOnCompletion {
            context.response().putHeader("Content-Type", "application/json; charset=UTF-8")
            val error = future.getCompletionExceptionOrNull()
            if(error != null)
                context.response().end(
                        FailedReply(error)
                                .toJson()
                                .toBuffer()
                )
            else context.response().end(
                    SucceededReply(future.getCompleted())
                            .toJson()
                            .toBuffer()
            )
        }
    }

    override suspend fun asyncRun(context: RoutingContext): String {
        val jsonObject = JsonObject(context.bodyAsString)
        val taskID = jsonObject.getString("task_id")
        val certificateID = jsonObject.getString("certificate_id")
        val vertx = context.vertx()

        val buffer = awaitResult<Buffer> { h -> vertx.fileSystem().readFile("${PDFBuilder.config.savePDFPath}/$taskID/$certificateID.pdf", h) }
        return Base64.getEncoder().encodeToString(buffer.bytes)
    }
}